package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.enums.common.BusinessErrorEnum;
import com.example.demo.pojo.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author tds
 * @version 1.0.0
 * @Company
 * @ClassName UserDetailServiceImpl
 * @Description Spring Security用户信息相关。
 *  loadUserByUsername：根据登录用户名查询用户信息。用于后面的登录认证和权限校验。
 * @Date 2022-03-28 23:27
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {



    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户名是否存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new BusinessException(BusinessErrorEnum.USER_NOT_EXIST);
        }

        // todo 查询用户对应的权限
        // 这里的admin，normal是权限，ROLE_abc表示abc角色（ROLE_是角色前缀）
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList("admin", "normal",
                "ROLE_abc"
//                , "/main.html"
        );

        return new org.springframework.security.core.userdetails.User(username, user.getPassword(), authorityList);
    }
}
